var URL_IsLogin = "http://cft.myspace.cn/testing/is_login/";
var URL_Login = "http://cft.myspace.cn/testing/login/";
var URL_Logout = "http://cft.myspace.cn/testing/logout/";
var URL_GetTestingAnnotation = "http://cft.myspace.cn/testing/annotation/";
var URL_RecordTesting = "http://cft.myspace.cn/testing/record/";
var URL_Auditing = "http://cft.myspace.cn/auditing/audit/";
var URL_DisplayCoverage = "http://cft.myspace.cn/auditing/display_coverage/";

function onTabSelect(event) {
	Application.activeWindow.activeTab.events.addListener("load", preLoad);
	log("listenerAdded");
}

Application.activeWindow.events.addListener("TabSelect", onTabSelect);

function log(asMsg) {
	Application.console.log(asMsg);
}

function preLoad() {
	if (content.document.body.innerHTML == "") {
		return false;
	}
	if (content.location.href.indexOf("http://cft.myspace.cn/admin") < 0) {
		isLogin();
	}
	
	var lbJquery = false, lbAnalysis = false, lbTesting = false,lbRecord=false;
	includeUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js",function() {
		lbJquery = true;
		callback();
	});
	includeUrl("http://cft.myspace.cn/site-media/analysis.js", function() {
		lbAnalysis = true;
		callback();
	});
	includeUrl("http://cft.myspace.cn/site-media/testing.js", function() {
		lbTesting = true;
		callback();
	});
	includeUrl("http://cft.myspace.cn/site-media/recorder.js",function() {
		lbRecord=true;
		callback();
	});
	includeUrl("http://cft.myspace.cn/site-media/style.css", null, "css");
	function callback() {
		if (lbJquery && lbAnalysis && lbTesting &&lbRecord) {
			log("entering abcd........");
			if(content.analysis_script_loaded == undefined ||
					content.recorder_script_loaded== undefined ||
					content.testing_script_loaded==undefined
					)
			{
				
				log("waiting....200 milliseconds");
				log(String(content.analysis_script_loaded));
				log(String(content.recorder_script_loaded));
				log(String(content.testing_script_loaded));
				setTimeout(callback,2000);
				return;
			}
			//got annotation data
			ajax( {
				url :URL_GetTestingAnnotation,
				method :"POST",
				data :encodeJson( {
					"url" :content.location.href
				}),
				callback : function(axData) {
				    log(encodeJson(axData));
					content.displayAnnotation(axData);
				}
			});
			content.alert(content.location.href);
			content.recordTesting();
			setInterval(sendTestingInfo, 3000);
		}
	}
}
function isLogin() {
	ajax( {
		url :URL_IsLogin,
		method :"GET",
		data :"",
		callback : function(aoData) {
			if (aoData.result == 0) {
				content.location.href = "http://cft.myspace.cn/admin";
			}
		}
	});
}
function login() {
	ajax( {
		url :URL_Login,
		method :"GET",
		data :"",
		callback : function(axData) {
			content.login();
		}
	});
}
function logout() {
	ajax( {
		url :URL_Logout,
		method :"POST",
		data :"",
		callback : function(aoData) {
			alert(aoData.msg);
		}
	});
}
function audit() {
	ajax( {
		url :URL_Auditing,
		method :"POST",
		data :encodeJson( {
			"url" :content.location.href
		}),
		callback : function(aoData) {
			if (aoData.result == 1) {
				window
						.open(
								'http://cft.myspace.cn/admin/testing/testresult/',
								'Test Result',
								'height=600, width=800, top=0, left=0, toolbar=no, menubar=no, scrollbars=no,location=no, status=no');
			} else {
				alert(aoData.msg);
			}
		}
	});
}
function display_coverage() {
	ajax( {
		url :URL_DisplayCoverage,
		method :"POST",
		data :encodeJson( {
			"url" :content.location.href
		}),
		callback : function(aoData) {
			if (aoData.result == 1) {
				content.displayCoverage(aoData.msg);
			} else {
				alert(aoData.msg);
			}
		}
	});
}

function sendTestingInfo() {
	// log("recording");
	var lxData = content.MX_TestingInfo;
	if (lxData.length < 1) {
		return false;
	}
	ajax( {
		url :URL_RecordTesting,
		method :"POST",
		data :encodeJson( {
			"url" :content.location.href,
			"type" :"form_element",
			"events" :lxData
		}),
		callback : function() {
			content.MX_TestingInfo = [];
		}
	});
}

function initUrl(spec) {
	var ios = Components.classes["@mozilla.org/network/io-service;1"]
			.getService(Components.interfaces.nsIIOService);
	return ios.newURI(spec, null, null);
}

function ajax(aoReq) {
	var req = new XMLHttpRequest();
	req.open(aoReq.method || 'GET', aoReq.url, true);
	req.onreadystatechange = function(aEvt) {
		if (req.readyState == 4) {
			if (req.status == 200) {
				if (aoReq.callback) {
					aoReq.callback(decodeJson(req.responseText));
				} else {
					return req.responseText;
				}
			} else {
				return "";
			}
		}
	};
	req.send(aoReq.data);
}

function str2Json(astr) {
	var ljson;
	if (typeof astr == "object") {
		return astr;
	}
	astr = (astr != null) ? astr.split("\n").join("").split("\r").join("") : "";
	if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(astr.replace(/\\./g, '@')
			.replace(/"[^"\\\n\r]*"/g, ''))) {
		if (astr != "") {
			ljson = eval('(' + astr + ')');
			return ljson;
		}
	}
	return {};
}
function encodeJson(object) {
	var json = Components.classes["@mozilla.org/dom/json;1"]
			.createInstance(Components.interfaces.nsIJSON);
	return json.encode(object);
}

function decodeJson(string) {
	var json = Components.classes["@mozilla.org/dom/json;1"]
			.createInstance(Components.interfaces.nsIJSON);
	return json.decode(string);
}
function json2Str(aobj) {
	switch (typeof (aobj)) {
	case 'string':
		return '"' + aobj.replace(/(["\\])/g, '\\$1') + '"';
	case 'array':
		return '[' + aobj.map(json2Str).join(',') + ']';
	case 'object':
		var string = [];
		for ( var property in aobj)
			if (typeof (aobj[property]) != "function")
				string
						.push(json2Str(property) + ':'
								+ json2Str(aobj[property]));
		return '{' + string.join(',') + '}';
	case 'number':
		if (isFinite(aobj))
			break;
	case 'function':
		return '""';
	case false:
		return 'null';
	}
	return String(aobj);
}

//test if the file is loaded to the url or not
function isFileLoaded(headElement,asType,asUrl)
{
	var elements=null;
	if(asType=="js")
		elements=headElement.getElementsByTagName("script");
	else
		elements=headElement.getElementsByTagName("link");
	for(var i=0;i<elements.length;i++)
	{
		log(String(elements[i].src));
		log(String(elements[i].href));
		if(asUrl==elements[i].src || asUrl==elements[i].href)
			return true;
	}
	return false;
}

function includeUrl(asUrl, afCallback, asType) {
	if (asUrl == null) {
		return false;
	}
	if (content.document.body.innerHTML == "") {
		return false;
	}
	var leHead = content.document.getElementsByTagName('head')[0];
	
	if (asType == null) {
		asType = "js";
	}	
	if(isFileLoaded(leHead,asType,asUrl))
		return false;
	
	var leTag = null;
	if (asType == "js") {
		leTag = content.document.createElement('script');
		leTag.setAttribute('type', 'text/javascript');
		leTag.setAttribute('src', asUrl);
	} else {
		leTag = content.document.createElement('link');
		leTag.setAttribute('rel', 'stylesheet');
		leTag.setAttribute('type', 'text/css');
		leTag.setAttribute('href', asUrl);
	}
	if (afCallback != null) {
		if (leTag.addEventListener) {
			leTag.addEventListener(
					"load", 
					afCallback,
					false);
		} else if (leTag.attachEvent) {
			leTag.attachEvent("onreadystatechange", function() {
				var target = window.event.srcElement;
				if (target.readyState == "loaded")
					afCallback.call(target);
			});
		}
	}
	leHead.appendChild(leTag);
	return true;
}